%I am trying to derive a function for calculating a moving/rolling 
%correlation for two vectors and speed is a high priority, since I have to
% use this on more than 5000 vectors of different lenghts. What I have (which 
%is too slow) is this:
clear all
 Data1 = rand(500,1);
Data2 = rand(500,1); 
 for i=100:200
Data1(i,1)=Data1(i,1)+sin(2*pi*i/100)*exp(-0.01*(i-100));
 end
 for i=100:200
Data2(i,1)=Data2(i,1)+sin(2*pi*i/100)*exp(-0.01*(i-100));
 end
 size(Data1)
 y = MovCorr(Data1,Data2);
N=500
size(y)
figure(1)
subplot(3,1,1)
plot(Data1(:,1))
subplot(3,1,2)
plot(Data2(:,1))
subplot(3,1,3)
plot(y(:,2))
t=100
x_cor=corr(Data1(t-20:t, 1),Data2(t-20:t,1),'rows','complete')
t=200
x_cor=corr(Data1(t-20:t, 1),Data2(t-20:t,1),'rows','complete')
t=300
x_cor=corr(Data1(t-20:t, 1),Data2(t-20:t,1),'rows','complete')
t=400
x_cor=corr(Data1(t-20:t, 1),Data2(t-20:t,1),'rows','complete')
t=400
x_cor=corr(Data1(t-20:t, 1),Data2(t-20:t,1),'rows','complete')
clear 
 Data1 = rand(500,1);
Data2 = rand(500,1); 
 for i=1:100
Data1(i,1)=Data1(i,1)+100*sin(2*pi*i/100)*exp(-0.01*(i-1));
 end
 for i=20:120
Data2(i,1)=Data2(i,1)+100*sin(2*pi*i/100)*exp(-0.01*(i-50));
 end
 N=130
for j=1:N
for k=1:N
    x_corr(k,j)=0;
    y_corr(k,j)=0;
    xy_corr(k,j)=0;
end
end
for mm=1+20:N  
    for j=1:20
  d1mm(mm,j)=Data2(mm-20+j,1);
  d2kk(mm,j)=Data2(mm-20+j,1); 
    end
end
    
    
    
      
     
   
     for kkk=1+20:1:N        
     for kk=1+20:1:N       
    x_corr2=0;
    y_corr2=0;
    xy_corr2=0;
    for j=1:1:20
   d2(j)=d2kk(kk,j);
    end
   for j=1:1:20
   d1(j)=d1mm(kk,j);
    end 
    for j=1:1:20
   xy_corr2=xy_corr2+d1(j)*d1(j);
   
   
     y_corr2=y_corr2+d1(j)^2;
   
     x_corr2=x_corr2+d2(j)^2;
    end
  
  x_corr1=sqrt(x_corr2);
    y_corr1=sqrt(y_corr2);
     xy_corr1=xy_corr2/(x_corr1*y_corr1);
   
  xy_corr(kk,mm)=xy_corr(kk,mm)+xy_corr1;
   %xy_corr(k,i)=xy_corr(k,1)+xy_corr1;
    y_corr(kk,mm)=y_corr(kk,mm)+y_corr1;
    x_corr(kk,mm)=x_corr(kk,mm)+x_corr1;
end 
end
x_corr1;
y_corr1;
for k=1+20:N
   x_corre(k,1)=0;
    y_corre(k,1)=0;
    xy_corre(k,1)=0; 
    for i=1+20:N
    y_corre(k,1)=y_corre(k,1)+y_corr(k,i);
    x_corre(k,1)=x_corre(k,1)+x_corr(k,i);
    xy_corre(k,1)=xy_corre(k,1)+xy_corr(k,i);
    end
end
size(x_corre)
size(y_corre)
size(xy_corre)
figure(2)
subplot(3,1,1)
plot(x_corre(:,1))
subplot(3,1,2)
plot(y_corre(:,1))
subplot(3,1,3)
plot(xy_corre(:,1))
    